#include "TraceShadow.h"
#include "Camera.h"

Color TraceShadow::TraceRay( const Ray& ray, int depth) const
{
    ContactData data = m_scene->CheckContact(ray);
    //if we are a shadow ray, and we hit something, we are in shadow!
    if(depth > 0 && data.m_hit && data.m_hitTarget != ray.m_hitObject)
    {
        Color c;
        c.m_a = 10.5f;
        return c;
    }
    else if(depth > 0) //else, we did not hit, so we are not in shadow.
    {
        Color c;
        c.m_a = 1.5f;
        return c;
    }
    if (data.m_hit)   
    {
        Color sc;
        //check if this is in shadow
        Ray shadow;
        shadow.m_origin = data.m_hitPoint;
        bool inShadow = false;

        for( unsigned int i = 0; i < m_scene->GetLights().size(); ++i)
        {
            Vec3 lightDir;
            if(m_scene->GetLights()[i]->IsDirectional())
                lightDir = m_scene->GetLights()[i]->GetDirection();
            else
            {
                Vec3 toLight = shadow.m_origin - m_scene->GetLights()[i]->GetPosition();
                toLight= toLight.normalise();
            }
            shadow.m_dir = lightDir.GetInverted();
            shadow.m_hitObject = data.m_hitTarget;
            sc = TraceRay(shadow, 10);
            if(sc.m_a == 10.5f)
                inShadow = true;
        }
        //if we are in shadow, return black
        if(sc.m_a == 10.5f)
            return data.m_hitTarget->GetColor() * 0.2f;

        return ShadeThis(data);
    }
    else
        return (m_scene->m_clearColor);
}
